import { ref, Ref } from 'vue'

const imgLoad = (src: string): Promise<boolean> => new Promise(resolve => {
  const img = new Image()
  img.onload = () => {
    resolve(true)
  }
  img.onerror = () => {
    resolve(true)
  }
  img.src = src
})

const goLoad = async (imgS: string[]) => {
  const arr = []
  for (let i = 0; i < imgS.length; i++) {
    arr.push(imgLoad(imgS[i]))
  }
  await Promise.all(arr)
}

export const imgRegular = /\.(png|jpe?g|gif)$/

export const useImage = (data: __WebpackModuleApi.RequireContext, needSrc?: string[]): Ref<boolean> => {
  const requireAll = (requireContext: any) => requireContext.keys().filter((key: string) => {
    const name = key.replace(imgRegular, '').substring(2)
    return !needSrc || needSrc.includes(name)
  }).map(requireContext)
  const loading = ref(false)
  const imgS = requireAll(data)
  if(imgS.length) {
    goLoad(imgS).then(() => {
      loading.value = true
    })
  } else {
    loading.value = true
  }
  return loading
}
